package com.fy.proj5_permission_transaction_cache.service.impl;

import com.fy.proj5_permission_transaction_cache.mapper.PermissionMapper;
import com.fy.proj5_permission_transaction_cache.mapper.RolePermissionMapper;
import com.fy.proj5_permission_transaction_cache.model.Permission;
import com.fy.proj5_permission_transaction_cache.service.CacheService;
import com.fy.proj5_permission_transaction_cache.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class PermissionServiceImpl implements PermissionService {

    @Autowired
    private PermissionMapper permissionMapper;
    
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    
    @Autowired
    private CacheService cacheService;

    @Override
    @Cacheable(value = "permissions", key = "'allPermissions'")
    public List<Permission> findAllPermissions() {
        return permissionMapper.findAll();
    }

    @Override
    @Cacheable(value = "permissions", key = "#id")
    public Permission findPermissionById(Long id) {
        return permissionMapper.findById(id);
    }

    @Override
    @Cacheable(value = "permissions", key = "#code")
    public Permission findPermissionByCode(String code) {
        return permissionMapper.findByCode(code);
    }

    @Override
    @Transactional
    @CacheEvict(value = {"permissions", "roles", "users"}, allEntries = true)
    public boolean deletePermission(Long id) {
        // 先删除角色权限关联
        rolePermissionMapper.deleteByPermissionId(id);
        // 再删除权限
        int result = permissionMapper.deleteById(id);
        return result > 0;
    }

    // addPermission方法已移除

    @Override
    @Transactional
    @Caching(
        put = @CachePut(value = "permissions", key = "#permission.id"),
        evict = @CacheEvict(value = "permissions", key = "'allPermissions'")
    )
    public boolean updatePermission(Permission permission) {
        int result = permissionMapper.update(permission);
        if (result > 0) {
            // 更新缓存
            cacheService.set("permission:" + permission.getId(), permission, 1, TimeUnit.HOURS);
            return true;
        }
        return false;
    }

    // deletePermission方法已移除

    @Override
    @Cacheable(value = "permissions", key = "'permissionsByRole:' + #roleId")
    public List<Permission> findPermissionsByRoleId(Long roleId) {
        return permissionMapper.findPermissionsByRoleId(roleId);
    }

    @Override
    @Cacheable(value = "permissions", key = "'permissionsByUser:' + #userId")
    public List<Permission> findPermissionsByUserId(Long userId) {
        return permissionMapper.findPermissionsByUserId(userId);
    }

    @Override
    public boolean hasPermission(Long userId, String permissionCode) {
        // 先查询缓存
        String cacheKey = "user_permission:" + userId + ":" + permissionCode;
        Boolean cachedResult = cacheService.get(cacheKey, Boolean.class);
        if (cachedResult != null) {
            return cachedResult;
        }
        
        // 缓存未命中，查询数据库
        List<Permission> permissions = permissionMapper.findPermissionsByUserId(userId);
        boolean hasPermission = permissions.stream().anyMatch(p -> permissionCode.equals(p.getCode()));
        
        // 缓存结果
        cacheService.set(cacheKey, hasPermission, 30, TimeUnit.MINUTES);
        
        return hasPermission;
    }
}